﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

using UploadManager;
//using StoreClientModule;
using UnityCore;


namespace MBB_Store_Sales_Report
{
    public partial class frmStatementOfAccount : Form
    {

        DataTable exportChargeInvoice = new DataTable();
        DataTable exportChargeInvoiceItem = new DataTable();
        DataTable exportChargePayments = new DataTable();
        DataTable exportChargeBalance = new DataTable();
        DataTable exportProfile = new DataTable();

        double AllInvoiceAmount = 0.0;
        double totalPayment = 0.0;


        SynchronizeData sync = new SynchronizeData();
        Threader t = new Threader();
        readDetails path = new readDetails();
        readDetails auto = new readDetails();
        autoDetails aSoldTo = new autoDetails();

        struct invoiceDetails
        {
            public string accountName;
            public string invoiceDate;
        }

        int pp = 1;
        int cnt = 0;

        public frmStatementOfAccount()
        {
            InitializeComponent();
            
            btnView.Click += new EventHandler(btnView_Click);
            btnClose.Click += new EventHandler(btnClose_Click);
            panel2.EnabledChanged += new EventHandler(panel2_EnabledChanged);

            sync.ProcessCompleted += new UnityCore.CoreHandler(sync_ProcessCompleted);
            sync.ProcessError += new UnityCore.CoreHandler(sync_ProcessError);

            btnPrint.Click += new EventHandler(btnPrint_Click);
            txtAcctName.KeyPress +=new KeyPressEventHandler(txtAcctName_KeyPress);
            cmbStore.SelectedIndexChanged += new EventHandler(cmbStore_SelectedIndexChanged);

        }

        void cmbStore_SelectedIndexChanged(object sender, EventArgs e)
        {
            auto.date = "";
            auto.remNode = cmbStore.Text;
            auto.fileName = "Charge Invoice";
            sync.Auto(auto);
        }
        void txtAcctName_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (txtAcctName.Text != "")
                {
                    if (e.KeyChar != (char)27 && e.KeyChar != (char)13)
                    {
                        if (txtAcctName.Items.Count > 0) txtAcctName.DroppedDown = true; else txtAcctName.DroppedDown = false;
                        aSoldTo.search = txtAcctName.Text;
                        aSoldTo.tbl = exportProfile;
                        sync.AutoSoldTo(aSoldTo);
                    }
                    else
                    {
                        txtAcctName.DroppedDown = false;
                    }
                }
                
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
        void sync_ProcessError(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg);
            });
        }

        void sync_ProcessCompleted(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "AutoSoldTo":
                        if (sync.ListAutoSoldTo.Length > 0)
                        {
                            txtAcctName.Items.Clear();
                            txtAcctName.Items.AddRange(sync.ListAutoSoldTo);
                            txtAcctName.SelectionStart = txtAcctName.Text.Length;
                        }
                        break;
                    case "GetStores":
                        cmbStore.Items.AddRange(sync.stores);
                        break;
                    case "Auto":
                        exportProfile = sync.export.DefaultView.ToTable(true, new string []{"fSoldTo"});
                        //grd2.DataSource = exportProfile;
                        break;
                    case "ReadMany":
                        exportChargeInvoice = sync.exportTables[0];
                        exportChargeInvoiceItem = sync.exportTables[1];
                        exportChargePayments = sync.exportTables[2];
                        exportChargeBalance = sync.exportTables[3];

                        grd.DataSource = extractChargeInvoices(); 
                        grd.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        
                        double totalAmt = 0.0;
                        for (int i = 0; i < grd.Rows.Count; i++)
                        {
                            double _amt = 0.0;
                            _amt = double.Parse(grd.Rows[i].Cells["Amount"].Value.ToString());
                            totalAmt += _amt;
                        }
                        txtTotal.Text = Common.FormatCurrency(totalAmt);

                        grd2.DataSource = extractPayments();
                        grd2.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        txtPayment.Text = Common.FormatCurrency(totalPayment);

                        controlState(true);
                        break;
                }

            });
        }
        void ControlState(bool state)
        {
            btnView.Enabled = state;
            btnPrint.Enabled = state;
            pnlMsg.Visible = !state;
        }
        #region extract Data From File
        DataTable extractChargeInvoices()
        {
            DataTable dt = new DataTable();
            
            string[] sDate = new string[0];
            string[] sEDate = txtDate.Text.Split('/');


            dt.Columns.Clear();
            dt.Rows.Clear();

            dt.Columns.Add("Date of Invoices");
            dt.Columns.Add("Invoice Number");
            dt.Columns.Add("Amount");
            dt.Columns.Add("P.O. Number");
            int index = 0;
            int index2 = 0;

            AllInvoiceAmount = 0;
            for (int i = 0; i < exportChargeInvoice.Rows.Count; i++)
            {
                sDate = exportChargeInvoice.Rows[i]["fDate"].ToString().Split('/');
                if (txtAnnual.Checked == true)
                {
                    index = 1;
                    index2 = 2;
                }
                else
                {
                    index = 0;
                    index2 = 0;
                }
                string acctName = exportChargeInvoice.Rows[i]["fSoldTo"].ToString();
                if (acctName.Equals(txtAcctName.Text) && sEDate[index].Equals(sDate[index2]))
                {
                    DataRow dr = dt.NewRow();
                    string inv = exportChargeInvoice.Rows[i]["fInvoice"].ToString(); ;
                    dr["Date of Invoices"] = exportChargeInvoice.Rows[i]["fDate"].ToString();
                    dr["Invoice Number"] = exportChargeInvoice.Rows[i]["fInvoice"].ToString();
                    dr["P.O. Number"] = exportChargeInvoice.Rows[i]["fPO"].ToString();
                    double totalInvoiceAmount = 0.0;
                    double amt = 0;
                    double qty = 0;
                    double unitPrice = 0;
                    
                    for (int j = 0; j < exportChargeInvoiceItem.Rows.Count; j++)
                    {
                        qty = 0;
                        unitPrice = 0;
                        string inv_item = exportChargeInvoiceItem.Rows[j]["fInvoice"].ToString();
                        if (inv.Equals(inv_item))
                        {
                            double.TryParse(exportChargeInvoiceItem.Rows[j]["fQty"].ToString(), out qty);
                            double.TryParse(exportChargeInvoiceItem.Rows[j]["fUnitPrice"].ToString(), out unitPrice);
                            amt = qty * unitPrice;
                            totalInvoiceAmount += amt;
                        }
                    }
                    
                    
                    dr["Amount"] = Common.FormatCurrency(totalInvoiceAmount);
                    AllInvoiceAmount += totalInvoiceAmount;
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }
        DataTable extractPayments()
        {
            DataTable tp = new DataTable();

            string[] arrInv = new string[grd.Rows.Count];
            for (int i = 0; i < arrInv.Length; i++)
            {
                arrInv[i] = grd.Rows[i].Cells[1].Value.ToString();
            }

            double totalBalance = 0.0;
            double balance = 0.0;
            for (int k = 0; k < exportChargeBalance.Rows.Count; k++)
            {
                for (int j = 0; j < arrInv.Length; j++)
                {
                    if (arrInv[j].Equals(exportChargeBalance.Rows[k]["fInvoice"].ToString()) && exportChargeBalance.Rows[k]["fStatus"].ToString().Equals("1"))
                    {
                        balance = double.Parse(exportChargeBalance.Rows[k]["fBalance"].ToString());
                        totalBalance += balance;
                    }
                }
            }

            txtBal.Text = Common.FormatCurrency(totalBalance);
            totalPayment = 0;
            tp.Columns.Clear();
            tp.Rows.Clear();

            tp.Columns.Add("Date");
            tp.Columns.Add("Account Name");
            tp.Columns.Add("OR Number");
            tp.Columns.Add("InvoiceNumber");
            tp.Columns.Add("Amount");

            for (int i = 0; i < arrInv.Length; i++)
            {
                for (int j = 0; j < exportChargePayments.Rows.Count; j++)
                {
                    if (arrInv[i].Equals(exportChargePayments.Rows[j]["fInvoiceNumber"].ToString()))
                    {
                        DataRow dr = tp.NewRow();
                        dr["Date"] = exportChargePayments.Rows[j]["fDateReceived"].ToString();
                        dr["Account Name"] = exportChargePayments.Rows[j]["fAccountName"].ToString();
                        dr["OR Number"] = exportChargePayments.Rows[j]["fORNumber"].ToString();
                        dr["InvoiceNumber"] = exportChargePayments.Rows[j]["fInvoiceNumber"].ToString();
                        dr["Amount"] = exportChargePayments.Rows[j]["fAmount"].ToString();
                        double amt = double.Parse(exportChargePayments.Rows[j]["fAmount"].ToString());
                        tp.Rows.Add(dr);

                        totalPayment += amt;
                    }
                }
            }
            return tp;
        }
        #endregion

        void btnPrint_Click(object sender, EventArgs e)
        {
            if (grd.Rows.Count > 0)
            {
                PrintDocument pd = new PrintDocument();
                pd.DocumentName = lblText.Text;
                pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
                PrintDialog pdlg = new PrintDialog();
                pdlg.Document = pd;
                if (pdlg.ShowDialog() == DialogResult.OK)
                {
                    PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                    ppdlg.Document = pd;
                    //Tracking.EnterLog("Price Table is printed.", DateTime.Now.ToString());
                    ppdlg.ShowDialog();
                }
            }
        }
        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0, y2=0, tmp = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left;
            float rm = e.PageBounds.Width - 100;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();
            float tmpStx = 0;
            
            //Header
            y = 150;
            y2 = 150;

            cFont = new Font("Courier New", 12f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString(Common.lStoreName, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 50, sf);
            e.Graphics.DrawString(Common.lStoreAddress, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 70, sf);

            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("STATEMENT OF ACCOUNT ", new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 90, sf);

            sf.Alignment = StringAlignment.Near;
            string str = txtAcctName.Text;
            e.Graphics.DrawString(str, cFont, Brushes.Black, lm, y, sf);

            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("As Of "+DateTime.Now.ToShortDateString(), cFont, Brushes.Black, rm, y, sf);
            //Column Header
            y += ht;
            y2 += ht;

            e.Graphics.FillRectangle(Brushes.LightGray, lm, y, rm - lm, ht);
            e.Graphics.DrawRectangle(new Pen(Brushes.Black), lm, y, rm - lm, ht);
            

            sf.Alignment = StringAlignment.Center;
            float cx = lm + (((rm - lm) * 30) / 100);
            float tx = lm + (((rm - lm) * 15f) / 100);
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Date of Invoices", cFont, Brushes.Black, tx, y, sf);
            
            cx += ((rm - lm) * 25) / 100;
            tx = cx - ((rm - lm) * 25) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Invoice Number", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 20) / 100;
            tx = cx - ((rm - lm) * 20) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("P.O. Number", cFont, Brushes.Black, tx, y, sf);

            tx += ((rm - lm) * 25) / 100;
            e.Graphics.DrawString("Amount", cFont, Brushes.Black, tx + 25, y, sf);
            
            //Data
            
            y += ht * (1.5f);
            y2 += ht * (1.5f);
            ht = cFont.GetHeight(e.Graphics);
            lpp = (bm - y) / ht;
            int cl = 0;
            float stx = 0, stx2 = 0; 
            
            while (cl <= lpp && cnt < grd.Rows.Count)
            {
                sf.Alignment = StringAlignment.Near;
                stx = lm + 1;
                stx2 = lm + ((rm - lm) * 56) / 100;

                    str = grd.Rows[cnt].Cells["Date of Invoices"].Value.ToString();
                    e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                    stx += ((rm - lm) * 31) / 100;
                    str = grd.Rows[cnt].Cells["Invoice Number"].Value.ToString();
                    e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                    y += ht;
          
                    str = grd.Rows[cnt].Cells["P.O. Number"].Value.ToString();
                    e.Graphics.DrawString(str, cFont, Brushes.Black, stx2, y2, sf);

                    sf.Alignment = StringAlignment.Far;
                    stx2 += ((rm - lm) * 44) / 100;
                    str = grd.Rows[cnt].Cells["Amount"].Value.ToString();
                    e.Graphics.DrawString(str, cFont, Brushes.Black, stx2, y2, sf);
                    y2 += ht;

                cnt++;
                cl++;
            }
            
            if (y2 >= y)
            {
                tmp = y2;
                tmpStx = stx2;
            }
            else
            {
                tmp = y;
                tmpStx = stx;
            }
            
            tmpStx = lm + ((rm - lm) * 56) / 100;
            
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Total", cFont, Brushes.Blue, lm + 1+ ((rm - lm) * 56) / 100, tmp, sf);
            sf.Alignment = StringAlignment.Far;
            tmpStx += ((rm - lm) * 44) / 100;
            e.Graphics.DrawString(Common.FormatCurrency(txtTotal.Text), cFont, Brushes.Blue, tmpStx, tmp, sf);
            tmpStx = lm + ((rm - lm) * 56) / 100;
            
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Total Payment", cFont, Brushes.Blue, lm + 1 + ((rm - lm) * 56) / 100, tmp + 15, sf);
            sf.Alignment = StringAlignment.Far;
            tmpStx += ((rm - lm) * 44) / 100;
            e.Graphics.DrawString(Common.FormatCurrency(txtPayment.Text), cFont, Brushes.Blue, tmpStx, tmp + 15, sf);

            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Balance", cFont, Brushes.Blue, lm + 1 + ((rm - lm) * 56) / 100, tmp+30, sf);
            sf.Alignment = StringAlignment.Far;
            
            e.Graphics.DrawString(Common.FormatCurrency(txtBal.Text), cFont, Brushes.Blue, tmpStx, tmp+30, sf);

            if (cnt < grd.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                e.HasMorePages = false;
                cnt = 0;
                pp = 1;
            }
              
        }
        
        void btnView_Click(object sender, EventArgs e)
        {
            if (txtAcctName.Text != "" && cmbStore.Text != "")
            {
                path.date = "";
                controlState(false);
                path.remNode = cmbStore.Text;
                path.fileNames.Clear();
                path.fileNames.Add("Charge Invoice");
                path.fileNames.Add("Charge Invoice Item");
                path.fileNames.Add("Charge Payments");
                path.fileNames.Add("Charge Balance");
                sync.ReadMany(path);
            }
        }
        void controlState(bool state)
        {
            btnView.Enabled = state;
            btnPrint.Enabled = state;
            txtAcctName.Enabled = state;
            pnlMsg.Visible = !state;
        }
        void panel2_EnabledChanged(object sender, EventArgs e)
        {
            if (!panel2.Enabled)
            {
                panel2.BackColor = Color.MidnightBlue;
            }
            else
            {
                panel2.BackColor = Color.RoyalBlue;
            }
        }
        void btnClose_Click(object sender, EventArgs e)
        {
            pnlExpensesListOnline.Dispose();
            this.Dispose();
        }
        public Panel PanelForm
        {
            get { return pnlExpensesListOnline; }
        }
        public void Initialize(string Title)
        {
            this.Select();
            lblText.Text = Title;

            sync.Stores();
            path.fileNames = new List<string>();
           
        }

        private void frmStatementOfAccount_Load(object sender, EventArgs e)
        {

        }
    }
}
